<template>
  <eip-modal
    :visible="visible"
    title="设置填写内容（用户点击按钮后，立即弹出对话框并填写指定的内容）"
    @close="cancel"
    :width="600"
  >
    <template slot="body">
      <a-form-model ref="form" layout="vertical" :model="form">
        <a-form-model-item label="填写对象">
          <a-radio-group v-model="form.target" @change="targetChange">
            <a-radio :value="1">当前记录 </a-radio>
            <a-radio :value="2">关联记录（单条） </a-radio>
          </a-radio-group>

          <div
            class="flex justify-begin align-center margin-top"
            v-if="
              form.target == eipZeroCodeFormSettingButtonFormTarget.correlation
            "
          >
            <label style="width: 80px">关联字段</label>
            <a-select
              placeholder="请选择关联字段"
              v-model="form.targetCorrelationKey"
              @change="targetCorrelationKeyChange"
              allowClear
            >
              <a-select-option
                :key="item.key"
                :value="item.key"
                v-for="item in correlationField"
                >{{ item.label }}</a-select-option
              >
            </a-select>
          </div>
        </a-form-model-item>

        <a-form-model-item label="填写内容">
          <a-radio-group
            v-model="form.write"
            @change="targetCorrelationKeyChange"
          >
            <a-radio :value="1">填写指定字段 </a-radio>
            <a-radio :value="2">新建关联记录 </a-radio>
          </a-radio-group>
          <vxe-grid
            v-if="form.write == 1"
            v-bind="correlationKeyGrid"
            class="margin-top"
          >
            <template #toolbarButtons>
              <a-popover placement="bottomLeft" trigger="click">
                <template slot="content">
                  <a-input-search
                    placeholder="请输入关键字"
                    style="width: 200px"
                  />
                  <div class="margin-top-xs">
                    <a-space>
                      <a-button type="primary" size="small">全选</a-button>
                      <a-button type="primary" size="small">清空</a-button>
                    </a-space>
                  </div>

                  <div
                    v-for="item in columns"
                    :key="item.key"
                    class="margin-top"
                  >
                    <a-checkbox
                      v-model="item.checked"
                      @change="filedChange(item)"
                    >
                      <a-icon v-if="item.cicon" :type="item.cicon" />
                      <svg v-else-if="item.icon" class="icon">
                        <use :xlink:href="`#${item.icon}`" class="use"></use>
                      </svg>
                      <a-icon v-else type="database"></a-icon>
                      <span class="overflow_ellipsis">{{ item.label }}</span>
                    </a-checkbox>
                  </div>
                </template>

                <vxe-button status="primary" @click="(e) => e.preventDefault()"
                  >选择填写字段</vxe-button
                >
              </a-popover>
            </template>

            <template #label="{ row }">
              <a-icon v-if="row.cicon" :type="row.cicon" />
              <svg v-else-if="row.icon" class="icon">
                <use :xlink:href="`#${row.icon}`" class="use"></use>
              </svg>
              <a-icon v-else type="database"></a-icon>
              <span class="overflow_ellipsis">{{ row.label }}</span>
            </template>

            <template #attribute="{ row }">
              <a-select
                v-model="row.attribute"
                v-if="
                  ![
                    eipZeroCodeControl.divider,
                    eipZeroCodeControl.card,
                    eipZeroCodeControl.tabs,
                    eipZeroCodeControl.collapse,
                    eipZeroCodeControl.grid,
                    eipZeroCodeControl.table,
                    eipZeroCodeControl.formulaNumber,
                    eipZeroCodeControl.otherField,
                    eipZeroCodeControl.total,
                  ].includes(row['type'])
                "
              >
                <a-select-option :value="1">只读</a-select-option>
                <a-select-option :value="2">填写</a-select-option>
                <a-select-option :value="3">必填</a-select-option>
              </a-select>
            </template>

            <template #default="{ row }">
              <a-input
                v-if="
                  ![
                    eipZeroCodeControl.divider,
                    eipZeroCodeControl.card,
                    eipZeroCodeControl.tabs,
                    eipZeroCodeControl.collapse,
                    eipZeroCodeControl.grid,
                    eipZeroCodeControl.table,
                    eipZeroCodeControl.formulaNumber,
                    eipZeroCodeControl.otherField,
                    eipZeroCodeControl.total,
                  ].includes(row['type'])
                "
              ></a-input>
            </template>

            <template #operate="{ row }">
              <a-popconfirm
                ok-text="确定"
                cancel-text="取消"
                @confirm="tableDelRow(row)"
              >
                <template slot="title"> 确定删除选中 </template>
                <a-button type="danger" size="small" icon="delete"></a-button>
              </a-popconfirm>
            </template>
          </vxe-grid>
          <div
            class="flex justify-begin align-center margin-top"
            v-if="form.write == 2"
          >
            <label style="width: 80px">关联字段</label>
            <a-select
              placeholder="请选择关联字段"
              v-model="form.writeCorrelationKey"
            >
              <a-select-option
                :key="item.key"
                :value="item.key"
                v-for="item in writeCorrelationField"
                >{{ item.label }}</a-select-option
              >
            </a-select>
          </div>
        </a-form-model-item>
      </a-form-model>
    </template>
    <template slot="footer">
      <div class="flex justify-between align-center">
        <div></div>
        <a-space>
          <a-button @click="cancel"><a-icon type="close" />关闭</a-button>
          <a-button key="submit" type="primary" @click="ok"
            ><a-icon type="save" />提交</a-button
          >
        </a-space>
      </div>
    </template>
  </eip-modal>
</template>

<script>
import { findById } from "@/services/system/zerocode/run/edit";
export default {
  name: "button-form",
  data() {
    return {
      config: {
        labelCol: { span: 4 },
        wrapperCol: { span: 20 },
      },
      form: {
        target: 1, //填写对象1当前记录，2关联记录(单条)
        targetCorrelationKey: undefined, //2关联记录(单条)-关联字段
        write: 1, //指定填写字段1指定填写字段，2新建关联记录
        writeKey: [], //1指定填写字段
        writeCorrelationKey: undefined, //2新建关联记录对应的关联字段
      },
      correlationKeyGrid: {
        border: true,
        showOverflow: true,
        height: 300,
        toolbarConfig: {
          slots: {
            buttons: "toolbarButtons",
          },
        },
        columns: [
          {
            field: "label",
            title: "字段",
            slots: {
              default: "label",
            },
          },
          {
            field: "attribute",
            title: "属性",
            width: 100,
            slots: {
              default: "attribute",
            },
          },
          {
            field: "default",
            title: "默认值",
            slots: {
              default: "default",
            },
          },
          {
            title: "删除",
            width: 100,
            align: "center",
            slots: {
              default: "operate",
            },
          },
        ],
        data: [],
        columnJson: [],
      },
      columns: [],
      nowZeroCodeId: this.zeroCodeId,
      nowColumnJson: [], //当前表单列
      columnJson: [],
    };
  },

  computed: {
    /**
     * 其他字段
     */
    correlationField() {
      //关联表
      var correlation = this.nowColumnJson.filter(
        (f) =>
          f.type == "correlation" &&
          f.options.zeroCodeId &&
          f.options.type == "single"
      );
      return correlation;
    },

    /**
     * 新建关联记录
     */
    writeCorrelationField() {
      //关联表
      var correlation = this.columnJson.filter(
        (f) => f.type == "correlation" && f.options.zeroCodeId
      );
      return correlation;
    },
  },

  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
    },
    options: Object,
    zeroCodeId: String,
  },

  async mounted() {
    await this.initNow();
    this.form = Object.assign(this.form, this.options);
    let that = this;
    this.form.writeKey.forEach((item) => {
      that.correlationKeyGrid.data.push({
        key: item.key,
        label: item.label,
        type: item.type,
        icon: item.icon,
        cicon: item.cicon,
        checked: false,
        attribute: 1, //属性1只读，2填写，3必填
        default: {},
      });
    });
    //判断是否使用新建关联记录
    if (
      this.form.target ==
        this.eipZeroCodeFormSettingButtonFormTarget.correlation &&
      this.form.write == this.eipZeroCodeFormSettingButtonFormWrite.correlation
    ) {
      this.targetCorrelationKeyChange();
    }
  },
  methods: {
    async initNow() {
      let that = this;
      that.columns = [];
      var systemZeroCodeData = await findById(that.zeroCodeId);
      if (systemZeroCodeData.data.publicJson) {
        var publicJson = JSON.parse(systemZeroCodeData.data.publicJson);
        var columns = this.getAllColumns(publicJson.list);
        that.nowColumnJson = columns;
        that.nowColumnJson
          .filter(
            (f) => ![this.eipZeroCodeControl.correlation].includes(f.type)
          )
          .forEach((item) => {
            that.columns.push({
              key: item.key,
              label: item.label,
              type: item.type,
              icon: item.icon,
              cicon: item.cicon,
              checked: false,
              attribute: 1, //属性1只读，2填写，3必填
              default: {},
            });
          });
      }
      if (systemZeroCodeData.data.columnJson) {
        that.columnJson = JSON.parse(systemZeroCodeData.data.columnJson);
      }
    },

    /**
     * 获取所有列
     * @param list
     */
    getAllColumns(list) {
      var columns = [];
      // 递归遍历控件树
      const traverse = (array) => {
        array.forEach((element) => {
          if (
            ["grid", "tabs", "collapse", "card", "batch"].includes(element.type)
          ) {
            columns.push(element);
            // 栅格布局 and 标签页
            element.columns.forEach((item) => {
              traverse(item.list);
            });
          } else if (element.type === "table") {
            // 表格布局
            columns.push(element);
            element.trs.forEach((item) => {
              item.tds.forEach((val) => {
                traverse(val.list);
              });
            });
          } else {
            columns.push(element);
          }
        });
      };
      traverse(list);
      return columns;
    },

    /**
     *
     * @param e
     */
    targetChange(e) {
      this.correlationKeyGrid.data = [];
      this.form.targetCorrelationKey = undefined;
      this.form.writeCorrelationKey = undefined;
      if (e.target.value == 1) {
        this.nowZeroCodeId = this.zeroCodeId;
        this.initNow();
      }
    },
    /**
     *
     * @param field
     */
    filedChange(field) {
      if (field.checked) {
        this.correlationKeyGrid.data.push(field);
      } else {
        this.$utils.remove(this.correlationKeyGrid.data, (f) => f == field);
      }
    },
    /**
     * 删除
     * @param row
     */
    tableDelRow(row) {
      this.$utils.remove(this.correlationKeyGrid.data, (f) => f == row);
    },
    /**
     * 初始化设计器
     */
    async initCorrection() {
      let that = this;
      that.columns = [];
      var systemZeroCodeData = await findById(that.nowZeroCodeId);
      if (systemZeroCodeData.data.columnJson) {
        that.columnJson = JSON.parse(systemZeroCodeData.data.columnJson);
        that.columnJson
          .filter(
            (f) => ![this.eipZeroCodeControl.correlation].includes(f.type)
          )
          .forEach((item) => {
            that.columns.push({
              key: item.key,
              label: item.label,
              type: item.type,
              icon: item.icon,
              cicon: item.cicon,
              checked: false,
              attribute: 1, //属性1只读，2填写，3必填
              default: {},
            });
          });
      }
    },

    /**
     * 修改字段
     */
    targetCorrelationKeyChange() {
      if (
        this.form.target ==
        this.eipZeroCodeFormSettingButtonFormTarget.correlation
      ) {
        this.correlationKeyGrid.data = [];
        var find = this.$utils.find(
          this.nowColumnJson,
          (f) => f.key == this.form.targetCorrelationKey
        );
        this.nowZeroCodeId = find.options.zeroCodeId;
        this.initCorrection();
      }
    },
    /**
     * 取消
     */
    cancel() {
      this.$emit("update:visible", false);
    },
    /**
     * 确定
     */
    ok() {
      this.form.writeKey = this.correlationKeyGrid.data;
      this.$emit("ok", this.form);
      this.cancel();
    },
  },
};
</script>
<style scoped lang="less">
/deep/ .ant-divider-horizontal {
  padding: 1px !important;
}
/deep/ .icon {
  margin: 0;
}
</style>
